<?php

class DefaultController extends MyAdminController
{
	
	public function actionIndex()
	{
		$model = new SettingsForm();
		
		if(isset($_POST['SettingsForm']))
		{
			$settings = (!empty($_POST['SettingsForm']['settings']))?$_POST['SettingsForm']['settings']:array();
			$configuration = (!empty($_POST['SettingsForm']['configuration']))?$_POST['SettingsForm']['configuration']:array();
			$model->attributes = array_merge($settings, $configuration);
			if ($model->validate(array_keys($settings)))
			{
				foreach($settings as $key=>$value)
				{
					$category = $model->mapCategory($key);
					Settings::model()->set($category, $key, $value);
				}
			}

			if ($model->validate(array_keys($configuration), false))
			{
				$paramsFile = Yii::app()->basePath.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'include'.DIRECTORY_SEPARATOR.'params.php';
				$paramsContent = "<?php\n";
				$paramsContent .= "return ";
				$paramsContent .= array2print($configuration);
				$paramsContent .= ";\n";
				$paramsContent .= "?>";
				if (is_file_writable($paramsFile))
				{
					file_put_contents($paramsFile, $paramsContent);
				}
			}
			
			$validationErrors = $model->getErrors();
			if (empty($validationErrors))
				$this->redirect(array('index'));
		}
		$settings=array();
		foreach ($model->getCategories() as $category)
		{
			$categorySettings = Settings::model()->get($category);
			if (!empty($categorySettings))
				$settings = array_merge($settings, $categorySettings);
		}
		
		$configuration=array();;
		foreach ($model->getConfigurationKeys() as $key)
		{
			$configuration[$key] = Yii::app()->params[$key];
		}
		
		$model->attributes = array_merge($settings, $configuration);
		
		/* set default values if needed*/
		if (empty($model->attributes['siteName']))
				$model->setAttributes(array('siteName'=>Yii::app()->name));
		if (empty($model->attributes['systemEmail']))
				$model->setAttributes(array('systemEmail'=>Yii::app()->user->getState('email')));
		
		$this->render('index', array('model'=>$model));
	}
		
	public function actionAjaxClearCache()
	{
		if (Yii::app()->cache->flush())
			echo tt('Flushing cache done');
		else
			echo tt('Error flushing cache');
	}
	
	public function actionAjaxClearSeoUrl()
	{
		if (SeoRouting::model()->truncateTable() === 0)
			echo tt('SEO URLs cleared');
		else {
			echo tt('Error deleting SEO URLs');
		}
	}
}